package com.qms.tubu.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.qms.tubu.R;
import com.qms.tubu.activity.scenic.ModuleDetailActivity;
import com.qms.tubu.adapter.LoadMoreAdapter;
import com.qms.tubu.adapter.RecommendAdapter;
import com.qms.tubu.bean.RecommendBean;
import com.qms.tubu.decoration.RecommendDecoration;
import com.qms.tubu.tools.UrlConfig;
import com.qms.tubu.widget.LoadMoreRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import tool.lib.ToastTool;
import tool.lib.volley.ExErrorListener;
import tool.lib.volley.ExListener;
import tool.lib.volley.JsonRequest;
import tool.lib.volley.VolleyTool;

/**
 * Created by Mad on 2015/7/14.
 */
public class RecommendationFragment extends BaseFragment implements LoadMoreAdapter.OnItemClickListener,SwipeRefreshLayout.OnRefreshListener{
    private LoadMoreRecyclerView mRecommendRecycler;
    private LinearLayoutManager mLayoutManager;
    private RecommendAdapter mAdapter;
    private SwipeRefreshLayout refreshLayout;
    private int pageNum;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.fragment_recommendation,container,false);
        mRecommendRecycler= (LoadMoreRecyclerView) rootView.findViewById(R.id.recommend_recycler_view);
        refreshLayout= (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLayoutManager=new LinearLayoutManager(rootView.getContext());
        mRecommendRecycler.setLayoutManager(mLayoutManager);
        mRecommendRecycler.setItemAnimator(new DefaultItemAnimator());
        mRecommendRecycler.addItemDecoration(new RecommendDecoration(rootView.getResources().getDimensionPixelOffset(R.dimen.linear_item_space)));
        mRecommendRecycler.setOnLoadMoreListener(new LoadMoreRecyclerView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                requestMore();
            }
        });
        refreshLayout.setOnRefreshListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
                requestRefresh();
            }
        }, getResources().getInteger(R.integer.first_refresh_delay_time));
    }
    private void requestMore()
    {
        JsonRequest request=new JsonRequest(UrlConfig.getUrl(R.string.recommend_more),new ExListener(){
            @Override
            public void onResponse(JSONObject object) {
                super.onResponse(object);
                if(verifyResult.getResult()==0)
                {
                    try {
                        loadData(object.getString("recommend"));
                    } catch (JSONException e) {
                    }
                    return;
                }
                if(verifyResult.getResult()==-1)
                {
                    mRecommendRecycler.loadComplete(0);
                    return;
                }
                mRecommendRecycler.loadFailed();
                ToastTool.showToast(verifyResult.getMsg());
            }
        },new ExErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                mRecommendRecycler.loadFailed();
            }
        });
        request.put("page", String.valueOf(pageNum));
        request.setTag(RecommendationFragment.class);
        VolleyTool.getInstance().add(request);
    }
    private void loadData(String data)
    {
        List<RecommendBean> list=JSON.parseArray(data,RecommendBean.class);
        mAdapter.getList().addAll(list);
        mAdapter.notifyDataSetChanged();
        mRecommendRecycler.loadComplete(list.size());
    }
    @Override
    public void onRefresh() {
        requestRefresh();
    }
    private void requestRefresh()
    {
        JsonRequest request=new JsonRequest(UrlConfig.getUrl(R.string.recommend_refresh),new ExListener(){
            @Override
            public void onResponse(JSONObject object) {
                super.onResponse(object);
                refreshLayout.setRefreshing(false);
                if(verifyResult.getResult()==0)
                {

                    try {
                        refreshData(object.getString("recommend"));
                        pageNum=1;
                    } catch (JSONException e) {

                    }
                    return;
                }
                else if(verifyResult.getResult()==-1)
                {
                    if(mAdapter==null)
                    {
                        mAdapter=new RecommendAdapter(rootView.getContext(),RecommendationFragment.this);
                        mAdapter.setOnItemClickListener(RecommendationFragment.this);
                        mRecommendRecycler.setAdapter(mAdapter);
                    }
                    else
                    {
                        mAdapter.getList().clear();
                        mAdapter.notifyDataSetChanged();
                    }
                    mRecommendRecycler.loadComplete(0);
                    pageNum=1;
                    return;
                }
                ToastTool.showToast(verifyResult.getMsg());
            }
        },new ExErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                refreshLayout.setRefreshing(false);
            }
        });
        request.setTag(RecommendationFragment.class);
        VolleyTool.getInstance().add(request);
    }
    private void refreshData(String data)
    {
        List<RecommendBean> list=JSON.parseArray(data,RecommendBean.class);
        if(mAdapter==null)
        {
            mAdapter=new RecommendAdapter(rootView.getContext(),this);
            mAdapter.setOnItemClickListener(this);
            mRecommendRecycler.setAdapter(mAdapter);
            mAdapter.setList(list);
            mAdapter.notifyDataSetChanged();
        }
        else
        {
            mAdapter.getList().clear();
            mAdapter.getList().addAll(list);
            mAdapter.notifyDataSetChanged();
        }
        mRecommendRecycler.loadComplete(list.size());
    }
    @Override
    public void onItemClick(View view, int position, long itemId) {
        startActivity(new Intent(rootView.getContext(), ModuleDetailActivity.class));
    }
}
